// pages/list.js
let app = getApp();
const {Tool, API, throttle, Storage} = global.$util

Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    fixTop: 0,
    goodsList: [],
    isLoading: false,
    isMore: true,
    page: 1,
    tipVal: '', // 默认是无 取值 1 2 3
    currentPage: 1, // 当前的页数
    pageSize: 10, // 每次加载请求的条数 默认10
    params: {},
    isAjax: false 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    Tool.isIPhoneX(this)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().init();
    this.getProdList()
  },

  fixedTop() {
    const query = wx.createSelectorQuery()
    const tabBar = query.select('#tabBar').boundingClientRect((res) => {
        this.setData({ fixTop: res.top })
    }).exec()
  },
  /**
     * 获取商品
     */
    getProdList() {
      if (this.data.isAjax) return
      this.data.isAjax = true
      const params = {
        ...this.data.params,
        pageNum: this.data.currentPage,
        shopId: Storage.getShopId(),
        pageSize: this.data.pageSize
      }
      API['getProductList'](params).then((data) => {
        let datas = data.data || {}
            if (datas.total > 0) {
                let isMore = Tool.hasNextPage(this.data.currentPage, this.data.pageSize, datas.total, datas.rows.length)
                this.setData({
                  goodsList: this.data.goodsList.concat(datas.rows || []),
                  tipVal: '',
                  isMore: isMore,
                }, ()=> {
                    this.data.loadMoreView = this.selectComponent(".loadMoreView")
                    this.data.loadMoreView.loadMoreComplete()
                })
            } else if (!datas.total) {
                this.setData({
                    tipVal: 2,
                    goodsList: [],
                    isMore: false
                })
            }
            this.data.isAjax = false
      }).catch(err => {
            if (this.data.params.page > 1) {
                this.data.currentPage--
            }
            this.data.isAjax = false
      })
  },
  onScroll() { // 向下滑动的时候请求数据
    this.data.loadMoreView.loadMore()
  },
  _loadMoreListener(){
      if (this.data.isAjax) return
      let page = this.data.currentPage
      page += 1
      let {params} = this.data
      params.pageNum = page

      this.data.params = params
      this.data.currentPage = page
      this.getProdList(this.data.params)
  },

  toDetail: throttle(function (e) {
    let id = e.currentTarget.dataset.id
    Tool.navigateTo(`/pages/good/detail/detail?id=${id}`);
  }),
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})